package com.ostrich.cloud.ostrichGoodsService.app.createJob;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Component
@Slf4j
public class XxlJobManager {

    @Resource
    private RestTemplate restTemplate;

    @Value("${xxl.job.admin.addresses}")
    private String adminAddress;

    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${application.owner.email}")
    private String alertEmail;

    public void removeJob(int jobId){
        String url = adminAddress + "/jobinfo/innerRemove?id="+jobId;

        ReturnT result = restTemplate.getForObject(url, ReturnT.class);
        if (result.getCode()!=200){
            throw new RuntimeException("删除失败");
        }
    }

    /**
     *
     * @param param
     * @return jobId
     */
    public int createJob(XxlJobCreateParam param){
        XxlJobInfo jobInfo = new XxlJobInfo();

        //其他同名参数
        BeanUtils.copyProperties(param,jobInfo);
        //重命名的参数
        jobInfo.setJobGroup(param.getExecutorId());
        //默认参数
        jobInfo.setScheduleType("CRON");
        jobInfo.setMisfireStrategy("DO_NOTHING");
        jobInfo.setExecutorRouteStrategy("FIRST");
        jobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
        jobInfo.setGlueType("BEAN");
        jobInfo.setTriggerStatus(0);
        jobInfo.setAuthor(applicationName);
        jobInfo.setAlarmEmail(alertEmail);
        String url = adminAddress + "/jobinfo/innerAdd";
        log.info("job:{}，url:{}",jobInfo,url);
        jobInfo.setTriggerStatus(1);
        ReturnT<String> result = restTemplate.postForObject(url, jobInfo, ReturnT.class);
        log.info("创建结果：{}",result);

        if(result.getCode()!=200){
            throw new RuntimeException("新增订单延时取消任务失败：["+result.getMsg()+"]");
        }

        return Integer.parseInt(result.getContent());
    }
}
